<?php
/**
 * Created by PhpStorm.
 * User: xieky
 * Date: 2017/8/4
 * Time: 17:14
 */

namespace common\services\myhtsq;

use common\entities\myhtsq\CarryoverTimeEntity;
use common\services\BaseService;
use common\repositories\myhtsq\ContractRevenueRepository;
use common\repositories\myhtsq\ContractRevenueCarryoverRepository;
use common\entities\myhtsq\ContractRevenueEntity;
use common\entities\myhtsq\ContractRevenueCarryoverEntity;
use common\entities\myhtsq\ContractRevenueCarryoverLogEntity;
use common\support\StringHelper;
use common\entities\ConfigEntity;
use common\support\DateTimeHelper;

class IncomeService extends BaseService
{
    private static $sheetIndex = 0;
    /**
     * 构造函数
     */
    public function __construct() {

    }

    public static function getIncomeList($incometype,$pageIndex,$pageSize,$keyword,$confirmtype,$incomeresource){
        $data = ContractRevenueRepository::getIncomeList($incometype,$pageIndex,$pageSize,$keyword,$confirmtype,$incomeresource);
        return $data;
    }

    public static function getCarryoverInfo(){
        $data = [];
        $row = ContractRevenueCarryoverLogEntity::find()
            ->where(['carryover_type'=>0])
            ->orderBy('created_on desc')
            ->limit(1)
            ->one();
        if(!empty($row)){
            $data['createon_0'] = empty($row['created_on'])?'':$row['created_on'];
            $data['createby_0'] = empty($row['created_by'])?'':$row['created_by'];
        }
        $row = ContractRevenueCarryoverLogEntity::find()
            ->where(['carryover_type'=>1])
            ->orderBy('created_on desc')
            ->limit(1)
            ->one();
        if(!empty($row)){
            $data['createon_1'] = empty($row['created_on'])?'':$row['created_on'];
            $data['createby_1'] = empty($row['created_by'])?'':$row['created_by'];
        }
        $row = ContractRevenueCarryoverLogEntity::find()
            ->where(['carryover_type'=>9])
            ->orderBy('created_on desc')
            ->limit(1)
            ->one();
        if(!empty($row)){
            $data['createon_9'] = empty($row['created_on'])?'':$row['created_on'];
            $data['createby_9'] = empty($row['created_by'])?'':$row['created_by'];
        }
        return $data;
    }

    /**
     * 进行结转结算
     * @param $stype    是全部结转,还是按照分类结转,0,1,9
     * @param $revenueid  针对单个记录调整后,重新计算单个收入项
     * @return string
     */
    public function doCarrover($stype){
        $iscommit = true;
        $carrovertime = CarryoverTimeEntity::find()->all();
        if(empty($carrovertime)){
            return '未设置结转期间,无法进行结转!';
        }
        if(count($carrovertime)>1){
            return '结转期间时间设置有误,请先检查处理!';
        }
        $trans = CarryoverTimeEntity::getDb()->beginTransaction();
        $data = ContractRevenueRepository::getCarryoverData($stype);
        foreach($data as $item){
            $confirmtype = $item['confirm_type'];
            if($confirmtype == 0){      //一次性
                $result = $this->doCarryoverOneTime($item);
                if(!$result){
                    $iscommit = false;
                    $trans->rollBack();
                }
            }
            if($confirmtype == 1){      //按租期
                $result = $this->doCarryoverByTime($item);
                if(!$result){
                    $iscommit = false;
                    $trans->rollBack();
                }
            }
        }
        if($iscommit){
            $trans->commit();
            $this->saveLog($stype);
        }
        return $result;
    }

    private function doCarryoverOneTime($item){
        if($item['right_begin_time']<=$item['carryover_end_time'] || $item['right_end_time']<=$item['carryover_end_time']) {
            $thisperiodconfirmamount = $item['amount'];
            $thisperiodconfirmtotalamount = $thisperiodconfirmamount;
            $lastperiodtotalconfirmamount = 0;
            $waitconfirmamount = 0;
        }
        if(!empty($item['carryover_id'])){
            ContractRevenueCarryoverEntity::deleteAll(['carryover_id'=>$item['carryover_id']]);
        }
        $result = ContractRevenueRepository::saveCarryoverData($item['revenue_id'],$item['carryover_begin_time'],$item['carryover_end_time'],$thisperiodconfirmamount,$thisperiodconfirmtotalamount,$lastperiodtotalconfirmamount,$waitconfirmamount);
        return $result;
    }

    private function doCarryoverByTime($item){
        if(!empty($item['carryover_id'])){
            ContractRevenueCarryoverEntity::deleteAll(['carryover_id'=>$item['carryover_id']]);
        }

        //还没开始使用,只生成空记录,不实际结转
        if($item['right_begin_time']>$item['carryover_end_time']) {
            $thisperiodconfirmamount = 0;
            $thisperiodconfirmtotalamount = 0;
            $lastperiodtotalconfirmamount = 0;
            $waitconfirmamount = $item['amount'];
        }else{
            $carryover = ContractRevenueRepository::getLatestCarroverByReveId($item['revenue_id']);
            if(empty($carryover)){
                $carryoverlastperiodtotalconfirmamount = 0;
            }else{
                $carryoverlastperiodtotalconfirmamount = $carryover->this_period_confirm_total_amount;
            }
            $date_diff1 = date_diff(date_create($item['carryover_end_time']),date_create($item['right_begin_time']))->days;
            $date_diff2 = date_diff(date_create($item['right_end_time']),date_create($item['right_begin_time']))->days;
            $carryoverrate = ($date_diff1+1)/($date_diff2+1);
            if($carryoverrate > 1){
                $carryoverrate = 1;
            }

            $thisperiodconfirmtotalamount = round($item['amount'] * $carryoverrate,2);
            $thisperiodconfirmamount = $thisperiodconfirmtotalamount - $carryoverlastperiodtotalconfirmamount;
            $lastperiodtotalconfirmamount = $carryoverlastperiodtotalconfirmamount;
            $waitconfirmamount = $item['amount'] - $thisperiodconfirmtotalamount;
        }
        $result = ContractRevenueRepository::saveCarryoverData($item['revenue_id'],$item['carryover_begin_time'],$item['carryover_end_time'],$thisperiodconfirmamount,$thisperiodconfirmtotalamount,$lastperiodtotalconfirmamount,$waitconfirmamount);
        return $result;
    }

    private function saveLog($stype){
        $log = new ContractRevenueCarryoverLogEntity();
        $log->carryover_log_id = StringHelper::uuid();
        $log->carryover_type = $stype;
        $log->created_on = ConfigEntity::getDbNowDate();
        $log->save();
    }

    public function exportIncome($incometype,$keyword,$confirmtype,$incomeresource){
        $objPHPExcel = new \PHPExcel();

        $this->exportIncomeExecl($objPHPExcel, $incometype,$keyword,$confirmtype,$incomeresource);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="合同清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 导出合同的产品信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     * 参考：\common\services\myhtsq\ContractService\getContractInfo->ContractApplicationRepository::getAllContractApplicationByContractId
     */
    private function exportIncomeExecl($objPHPExcel, $incometype,$keyword,$confirmtype,$incomeresource)
    {
        $data = ContractRevenueRepository::getIncomeList($incometype,0,0,$keyword,$confirmtype,$incomeresource,'export');
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('收入');

        //设置列标题
        $columnTitles = ['序号','客户信息','合同编号','所属区域','签约日期','录入日期','收入结转开始时间','权益日期','收入项编码','核算收入类别','确认方式','收入金额','累计已确认收入','待确认收入','收入来源','本期确认收入'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $val) {
                $type_name = $val['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'?'移动工程协同':$val['type_name'];
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $j-1); //序号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['cstname']); //客户信息
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编码
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['sign_date'])); //签约日期
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['input_date'])); //录入日期
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['carryover_begin_time'])); //收入结转开始时间
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['right_begin_time']).'至'.DateTimeHelper::getDate($val['right_end_time'])); //权益日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_code']); //收入项编码
                $i++;
                $activeSheet->setCellValue($i . $j, $type_name); //核算收入类别
                $i++;
                $activeSheet->setCellValue($i . $j, $val['confirm_type_name']); //确认方式
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']); //收入金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['total_confirm_amount']); //累计已确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['wait_confirm_amount']); //待确认收入
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_source']); //收入来源
                $i++;
                $activeSheet->setCellValue($i . $j, $val['this_period_confirm_amount']); //本期确认收入
                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列
    }

    /**
     * 获取当前活动表格
     * @param type $objPHPExcel
     * @return type
     */
    private static function getActiveSheet($objPHPExcel)
    {
        if (self::$sheetIndex == 0) {
            $objPHPExcel->setActiveSheetIndex(self::$sheetIndex);
            $activeSheet = $objPHPExcel->getActiveSheet();
        } else {
            $activeSheet = $objPHPExcel->createSheet(self::$sheetIndex);
        }
        self::$sheetIndex++;
        return $activeSheet;
    }

}